package com.example.rbacmanage.service.system.impl;

import com.alibaba.druid.util.StringUtils;
import com.example.rbacmanage.annotation.PermissionRange;
import com.example.rbacmanage.entity.system.Dept;
import com.example.rbacmanage.mapper.system.DeptMapper;
import com.example.rbacmanage.mapper.system.RoleDeptMapper;
import com.example.rbacmanage.service.system.DeptService;
import com.example.rbacmanage.vo.DeptTreeResp;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private RoleDeptMapper roleDeptMapper;
    @Override
    public void save(Dept dept) {
        Dept parent = deptMapper.queryOneById(dept.getParentId());
        if (parent != null){
            dept.setAncestors(parent.getAncestors()+","+dept.getParentId());
        }else{
            dept.setAncestors(dept.getParentId()+"");
        }
        deptMapper.insert(dept);
    }

    @Override
    public void remove(Long[] ids) {
        for(Long id:ids){
            deptMapper.del(id);
            //同事删除角色部门关系表
            roleDeptMapper.deleteByDeptId(id);
        }
    }
    @Override
    public void update(Dept dept) {
        Dept parent = deptMapper.queryOneById(dept.getParentId());
        Dept old = deptMapper.queryOneById(dept.getId());
        if (parent != null && old != null){
            String newAncestors = parent.getAncestors()+","+parent.getId();
            String oldAncestors = old.getAncestors();
            dept.setAncestors(newAncestors);
            //修改子元素关系
            Dept dept1 = new Dept();
            dept1.setParentId(dept.getId());
            List<Dept> children = deptMapper.list(dept1);
            for (Dept child :children){
                child.setAncestors(child.getAncestors().replaceFirst(oldAncestors,newAncestors));
                deptMapper.update(child);
            }
        }
        deptMapper.update(dept);
    }

    @Override
    public List<Dept> getAll(Dept dept) {
        return deptMapper.list(dept);
    }

    @Override
    @PermissionRange(deptAlias = "d")
    public PageInfo<Dept> getPage(Dept dept) {
        return new PageInfo<>(deptMapper.list(dept));
    }

    @Override
    public Dept getById(Long id) {
        return deptMapper.queryOneById(id);
    }

    @Override
    public Integer getCount(Dept dept) {
        return deptMapper.count(dept);
    }

    @PermissionRange(deptAlias = "d")
    @Override
    public List<DeptTreeResp> getTree(Dept dept) {
        List<Dept> depts = deptMapper.list(dept);
        //将list转换成树结构
        List<DeptTreeResp> deptList = new ArrayList<>();
        depts.forEach(d->{
            DeptTreeResp deptTreeResp = new DeptTreeResp();
            deptTreeResp.setLabel(d.getDeptName());
            deptTreeResp.setId(d.getId());
            deptTreeResp.setParentId(d.getParentId());
            deptTreeResp.setValue(d.getId());
            deptTreeResp.setDeptName(d.getDeptName());
            deptTreeResp.setSort(d.getSort());
            deptTreeResp.setStatus(d.getStatus());
            deptTreeResp.setContactPhone(d.getContactPhone());
            deptTreeResp.setContactUser(d.getContactUser());
            deptTreeResp.setCreateTime(d.getCreateTime());
            deptList.add(deptTreeResp);
        });
        if(!StringUtils.isEmpty(dept.getDeptName()) || !StringUtils.isEmpty(dept.getStatus())){
            return deptList;
        }
        return buildDeptTreeSelect(deptList);
    }

    private List<DeptTreeResp> buildDeptTreeSelect(List<DeptTreeResp> deptList) {
        List<DeptTreeResp> returnList = new ArrayList<>();
        List<Long> tempList = deptList.stream().map(DeptTreeResp::getId).collect(Collectors.toList());
        for (DeptTreeResp deptTreeResp: deptList){
            //如果是顶级节点，遍历该父节点的所有子节点
            if (!tempList.contains(deptTreeResp.getParentId())){
                recursionFn(deptList,deptTreeResp);
                returnList.add(deptTreeResp);
            }
        }
        if (returnList.isEmpty()){
            returnList = deptList;
        }
        return returnList;
    }
    //递归列表
    private void recursionFn(List<DeptTreeResp> deptList, DeptTreeResp deptTreeResp) {
        //得到子节点列表
        List<DeptTreeResp> childList = getChildList(deptList,deptTreeResp);
        deptTreeResp.setChildren(childList);
        for (DeptTreeResp child : childList){
            //是否有子孩子
            boolean hasChild = getChildList(deptList,child).size() > 0;
            if (hasChild){
                recursionFn(deptList,child);
            }
        }
    }
    //得到子节点列表
    public List<DeptTreeResp> getChildList(List<DeptTreeResp> deptList,DeptTreeResp deptTreeResp){
        List<DeptTreeResp> childList = new ArrayList<>();
        Iterator<DeptTreeResp> it = deptList.iterator();
        while (it.hasNext()){
            DeptTreeResp n = it.next();
            if (n.getParentId() != null && n.getParentId().equals(deptTreeResp.getId())){
                childList.add(n);
            }
        }
        return childList;
    }
}
